package com.ffy.controller;

import com.ffy.config.MinioConfig;
import com.ffy.result.Result;
import com.ffy.result.ResultUtil;
import com.ffy.service.MinioService;
import io.minio.ObjectStat;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@RequestMapping("/minio")
@RestController
@Api(tags = "MinIO文件接口")
public class MinioController {

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 使用MinIO上传文件
     * @param file 文件名称
     * @param bucketName 存储桶名
     */
    @ApiOperation(value = "使用minio文件上传")
    @PostMapping("/uploadFile")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "MultipartFile", name = "file", value = "上传的文件", required = true),
            @ApiImplicitParam(dataType = "String", name = "bucketName", value = "对象存储桶名称", required = false)
    })
    public Result uploadFile(MultipartFile file, String bucketName) {
        try {
            //获取存储桶名
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            //判断存储桶是否存在
            if (!minioService.bucketExists(bucketName)) {
                minioService.makeBucket(bucketName);
            }
            String fileName = file.getOriginalFilename();
            String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "")
                    + fileName.substring(fileName.lastIndexOf("."));
            minioService.putObject(bucketName, file, objectName);
            return ResultUtil.success(minioService.getObjectUrl(bucketName, objectName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.sendErrorMessage("上传失败");
        }
    }
    /**
     *使用MinIO下载文件
     * @param file 文件名
     * @param bucketName 存储桶名
     * @return
     */

    @ApiOperation("使用MinIO下载文件")
    @GetMapping("/downloadFile")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String",name = "file",value = "下载的文件",required = true),
            @ApiImplicitParam(dataType = "String",name = "bucketName",value = "对象存储桶名称",required = true)
    })
    public Result downloadFiel(HttpServletResponse response,@RequestParam("file")String file,@RequestParam String bucketName){
        try {
            //获取存储桶名
            bucketName=StringUtils.isNotBlank(bucketName) ? bucketName: minioConfig.getBucketName();
            //获取对象信息和对象的元数据
            ObjectStat objectStat=minioService.statObject(bucketName,file);
            //setContentType 设置发送到客户机响应的内容类型
            response.setContentType(objectStat.contentType());
            //设置响应头
            response.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(objectStat.name(), "UTF-8"));
            //文件流
            InputStream object=minioService.getObjectUrl(bucketName,file);
            //设置文件大小
            response.setHeader("Content-Length",String.valueOf(objectStat.length()));
            IOUtils.copy(object,response.getOutputStream());
            //关闭流
            object.close();
            return ResultUtil.success(minioService.getObjectUrl(bucketName,file));
        }catch (Exception e) {
            return ResultUtil.sendErrorMessage("下载失败");
        }
    }
}